#!/usr/bin/env python
# encoding: utf-8

from common.libs.Log import logger
from common.libs.Helper import getFormatTime, getCurrentTime


from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.mqttTest import Ui_Form

from .MqttConfigDialog import MqttConfigDialog
from .MqttThread import MqttThread 
from .TableView import TableView 
from .MessageTableView import MessageTableView

import PyQt5_stylesheets
import qtawesome as qta

class MqttTestWidget(QWidget, Ui_Form):
    conf = {}
    session = {}
    def __init__(self, parent = None, save_path=''):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("mqtt测试")
        self.uiInit()
        self.timerInit()
        self.signalInit()
        self.comboBoxSessionChanged()

    def uiInit(self):
        self.mqttConfigDialog = MqttConfigDialog()
        self.comboBox_session.addItems(self.mqttConfigDialog.getSessionNameList())
        self.messageTableView = TableView()
        self.messageTableView.setHeader(['事件', '主题', '消息', '服务质量', '时间'])
        self.publishTableView = TableView()
        self.publishTableView.setHeader(['主题', '消息', '服务质量'])
        self.subscribeTableView = TableView()
        self.subscribeTableView.setHeader(['主题', '服务质量'])
        self.verticalLayout_publish.addWidget(self.publishTableView)
        self.verticalLayout_subscribe.addWidget(self.subscribeTableView)
        self.verticalLayout_msg.addWidget(self.messageTableView)
        # 图标
        self.connect_icon = qta.icon('fa5s.circle', color='springgreen')
        self.disconnect_icon = qta.icon('fa5s.circle', color='red')
        self.pushButton_connect.setIcon(self.disconnect_icon)

    def timerInit(self):
        # 定时发布
        self.publish_timer = QTimer()
        self.publish_timer.timeout.connect(self.publish)
        # 开启线程
        self.mqtt_thread = MqttThread()

    def signalInit(self):
        # 选择会话
        self.comboBox_session.currentIndexChanged.connect(self.comboBoxSessionChanged)
        # mqtt 设置，连接，断开
        self.pushButton_session_set.clicked.connect(lambda:self.mqttConfigDialog.exec(self.comboBox_session.currentIndex()))
        self.pushButton_connect.clicked.connect(self.connect)
        self.pushButton_disconnect.clicked.connect(self.disconnect)
        # 订阅
        self.pushButton_subscribe.clicked.connect(self.subscribe)
        # 推送
        self.pushButton_publish.clicked.connect(self.publish)
        # 定时发送
        self.checkBox_publish_timer.clicked.connect(self.publishtimerChecked)
        # 清空消息 
        self.pushButton_msg_clear.clicked.connect(self.messageTableView.clearData)
        # mqtt消息绑定
        self.mqtt_thread.signal_on_connect.connect(self.onConnect)
        self.mqtt_thread.signal_on_disconnect.connect(self.onDisconnect)
        self.mqtt_thread.signal_on_subscribe.connect(self.onSubscribe)
        self.mqtt_thread.signal_on_message.connect(self.onMessage)

    def comboBoxSessionChanged(self):
        if self.comboBox_session.currentIndex() >= 0:
            session = self.mqttConfigDialog.getSessionByIndex(self.comboBox_session.currentIndex())
            publish = session['publish']
            subscribe = session['subscribe']
            self.publishTableView.clearData()
            self.subscribeTableView.clearData()
            for p in publish:
                self.publishTableView.addRow([p['topic'],p['msg'],p['qos']])
            for s in subscribe:
                self.subscribeTableView.addRow([s['topic'],s['qos']])

    def connect(self):
        if not self.mqtt_thread.is_connect:
            session = self.mqttConfigDialog.getSessionByIndex(self.comboBox_session.currentIndex())
            self.mqtt_thread.load_conf(session)
            self.mqtt_thread.start()
        else:
            QMessageBox.information(self,"提示","已连接服务器！", QMessageBox.Yes)

    def disconnect(self):
        self.mqtt_thread.stop()

    def subscribe(self):
        if not self.mqtt_thread.is_connect:
            QMessageBox.information(self,"提示","请连接服务器！", QMessageBox.Yes)
            return
        topics = [(d[0], int(d[1])) for d in self.subscribeTableView.getRows()]
        self.mqtt_thread.do_subscribe(topics)

    def publish(self):
        if not self.mqtt_thread.is_connect:
            QMessageBox.information(self,"提示","请连接服务器！", QMessageBox.Yes)
            self.publish_timer.stop()
            return
        msgs = self.publishTableView.getRows()
        for m in msgs:
            self.mqtt_thread.do_publish(m[0],m[1],m[2])

    def publishtimerChecked(self):
        if self.checkBox_publish_timer.isChecked():
            self.publish_timer.start(self.spinBox_publish_timer.value())
        else:
            self.publish_timer.stop()

    def onConnect(self):
        self.pushButton_connect.setIcon(self.connect_icon)
        self.comboBox_session.setEnabled(False)
        self.messageTableView.addRow(['连接服务器', '', '', '', getCurrentTime()])

    def onDisconnect(self):
        self.pushButton_connect.setIcon(self.disconnect_icon)
        self.comboBox_session.setEnabled(True)
        self.messageTableView.addRow(['连接断开', '', '', '', getCurrentTime()])
    
    def onSubscribe(self):
        self.messageTableView.addRow(['订阅成功', '', '', '', getCurrentTime()])
    
    def onMessage(self, topic, message, qos):
        self.messageTableView.addRow(['收到消息', topic, message, qos, getCurrentTime()])



if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    form = MqttTestWidget()
    form.show()
    app.exec_()
